package com.bluishoul.utils;

import java.io.IOException;
import java.util.List;

import my.mvc.RequestContext;

public class StorageService {
	public static final String DOMAIN_JSBIN = RequestContext.root()
			+ java.io.File.separator + "storage" + java.io.File.separator
			+ "jsbin" + java.io.File.separator;
	public static final int INIT_VERSION = 1;

	/**
	 * 添加一个文件，如果是第一次添加将创建版本号为1的文件，否则将会创建最大版本号+1的文件
	 * 
	 * @param domin
	 * @param key
	 * @param value
	 * @return version
	 * @throws IOException
	 */
	public static int add(String domin, String key, String value)
			throws IOException {
		if (FileService.isFileExist(domin, INIT_VERSION + "-" + key)) {
			StringBuilder s_key = new StringBuilder();
			int version = getMaxVersionByKey(domin, key) + 1;
			s_key.append(version);
			s_key.append("-");
			s_key.append(key);
			FileService.add(domin, s_key.toString(), value);
			return version;
		} else {
			FileService.add(domin, INIT_VERSION + "-" + key, value);
			return INIT_VERSION;
		}
	}
	
	public static int add(RequestContext rc,String domin, String key, String value) throws IOException{
		return add(domin, key, value);
	}

	/**
	 * 根据版本号加载value，version为-1表示加载最新版。
	 * 
	 * @param domin
	 * @param key
	 * @param version
	 * @return
	 * @throws IOException
	 */
	public static String getValueByKey(String domin, String key, int version)
			throws IOException {
		if (version >= INIT_VERSION)
			return FileService.getValueByKey(domin, version + "-" + key);
		return FileService.getValueByKey(domin, getMaxVersionByKey(domin, key)
				+ "-" + key);
	}

	/**
	 * 通过文件名得到版本号
	 * 
	 * @param name
	 * @return
	 */
	public static int getVersionByName(String name) {
		String v = name.split("-")[0];
		return Integer.parseInt(v);
	}

	/**
	 * 通过domin和key得到最大版本号
	 * 
	 * @param domin
	 * @param key
	 * @return
	 */
	public static int getMaxVersionByKey(String domin, String key) {
		List<String> name_list = FileService.getNameListByDomin(domin);
		int max_v = 0;
		for (String name : name_list) {
			int v = Integer.parseInt(name.split("-")[0]);
			if (v > max_v)
				max_v = v;
		}
		return max_v;
	}

	public static void main(String[] args) {
		try {
			String str = StorageService.getValueByKey(DOMAIN_JSBIN, "nkyghtuz",
					1);
			System.out.println(str.hashCode());
			str = str.replace("\r\n", "\\n");
			System.out.println(str.hashCode());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
